# -*- coding: utf-8 -*-

import os
import sys
import jinja2
import simplejson
import time
from openerp import http
from openerp.http import request
from openerp.osv import osv
from openerp.addons.website_mshop.pools import ModelPool, CursorProxy, common_functions, PageProxy, _slug
from weixin_enterprise import WeixinEnterprise
import datetime, logging
_logger = logging.getLogger(__name__)
SUPERUSER_ID = 1
if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'html'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.dftg_weixin', "html")

env = jinja2.Environment('<%', '%>', '${', '}', '%', loader=loader, autoescape=True)

class WxAppPunch(WeixinEnterprise):
    _app_xml_id = 'dftg_weixin.weixin_dftg_weixin_punch'

class WxAppPunchController(http.Controller):
    weixin_app = None
    
    def __init__(self):
        env.globals['_pool'] = ModelPool()
        env.globals['_cr'] = CursorProxy()
        env.globals['_page'] = PageProxy()
        env.globals['_slug'] = _slug
        env.globals.update(common_functions)
        env.filters['tojson'] = simplejson.dumps
        self.weixin_app = WxAppPunch()
    
    # 微信回调入口网址
    @http.route('/weixin/app/punch', auth='public')
    def weixin(self, **kw):
        result = self.weixin_app.process(request.httprequest.args, request.httprequest.data)
        return result


class weixin_punch(osv.osv):
    _inherit = 'weixin.punch'
    
    def getYesterday(self):
        today = datetime.date.today()
        oneday = datetime.timedelta(days=1)
        yesterday = today - oneday
        return yesterday

    def time_stamp_reduce_hours(self, time_stamp, hours=8):
        return time_stamp - hours*3600

    def chunks(self, arr, n):
        return [arr[i:i + n] for i in range(0, len(arr), n)]

    def get_today_punch_record(self, cr, uid, opencheckindatatype=3, some_start_date=False,  some_end_date=False,context=None):
        """
        :param opencheckindatatype: 本次获取打卡记录的类型  # opencheckindatatype 。1：上下班打卡；2：外出打卡；3：全部打卡
        :param some_start_date: 开始时间 时间字符串
        :param some_end_date: 结束时间 时间字符串
        通过格式化输出
        """
        leave_obj = self.pool.get('work.overtime.leave')
        t = time.localtime(time.time() - 86400)
        time_start = time.mktime(time.strptime(some_start_date or time.strftime('%Y-%m-%d 00:00:00', t), '%Y-%m-%d %H:%M:%S'))
        time_end = time.mktime(time.strptime(some_end_date or time.strftime('%Y-%m-%d 23:59:59', t), '%Y-%m-%d %H:%M:%S'))
        starttime = self.time_stamp_reduce_hours(long(time_start))
        endtime = self.time_stamp_reduce_hours(long(time_end))
        wxapppunch, all_record, all_users = WxAppPunch(), [], []
        users = wxapppunch.wxapi.department_users(1, fetch_child=1)
        if users[0] and users[0].get('errcode') == 0:
            all_users = [user.get('userid') for user in users[0].get('userlist', [])]
        user_ids = self.pool.get("weixin.contacts").search(cr, uid, [('is_disabled', '=', False),
                                                                     ('id', 'in', all_users)], context=context)
        for ids in self.chunks(user_ids, 100):
            try:
                all_record = wxapppunch.wxapi.get_punch_time(opencheckindatatype, starttime, endtime,
                                                             [str(user_id) for user_id in ids])
            except Exception as exc:
                self.pool.get('sale.order').send_message( cr, uid, SUPERUSER_ID,
                                                          '大事不好啦，自动获取打卡记录过程中出错了！', context=None)
                _logger.error(u"weixin_punch 错误详细原因%s" % (exc))
                continue
            if all_record and all_record[0] and all_record[0].get('errcode') == 0:
                for record in all_record[0].get('checkindata'):
                    date_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(record.get('checkin_time'))))

                    weixin_row = self.pool.get('weixin.contacts').browse(cr, uid, int(record.get('userid')),
                                                                         context=context)
                    leave_ids = leave_obj.search(cr, uid, [('date', '=', date_str[:10]),
                                                           ('type', '=', 'overtime'),
                                                           ('user_id', '=', weixin_row.odoo_user_id.id)], context=context)
                    record_id = self.search(cr, uid, [('checkin_time', '=', record.get('checkin_time')),
                                                      ('userid', '=', int(record.get('userid'))),
                                                      ('checkin_type', '=', record.get('checkin_type'))], context=context)
                    if record_id:
                        continue
                    record.update({'date': date_str})
                    if not record.get('groupname'):
                        record.update({'groupname': '东方团购中心正常上班打卡规则'})
                    if not record.get('checkin_type'):
                        record.update({'checkin_type': '东方团购中心正常上班打卡规则'})
                    punch_id = self.create(cr, uid, record, context=context)
                    if record.get('checkin_type') == '上班打卡':
                        leave_obj.write(cr, uid, leave_ids, {'punch_in_time_id': punch_id}, context=context)
                    elif record.get('checkin_type') == '下班打卡':
                        leave_obj.write(cr, uid, leave_ids, {'punch_out_time_id': punch_id}, context=context)
        else:
            if not user_ids:
                self.pool.get('sale.order').send_message(cr, uid, SUPERUSER_ID,
                                                         '大事不好啦，本次获取一条记录都没获取到！！', context=None)
                _logger.error(u"weixin_punch错误代码%s，详细原因%s"%(all_record[0].get('errcode'), all_record[0].get('errmsg')))

